<script setup lang="js">
import { ref, reactive, onMounted, defineEmits } from 'vue'
import { NButton, NForm, NInput, NRadio, NRadioGroup, NFormItem, NSelect } from 'naive-ui'
import {
  setItem,
  getItem,
  randomSelectRadioBySelectors,
  delay,
  getRandomIntInRange,
} from '../utils'
import { allowHost } from '../data'
const emit = defineEmits()

const runStatus = ref(false)
const message = ref('')
const formRef = ref(null)
const formValue = reactive({
  age: [25, 60],
  education: ['Associate Degree', 'College Degree (such as B.A., B.S.)','Masters degree','Doctorate degree'],
  employment: ['Employed full-time', 'Employed part-time'],
  income: ["$75,000 to $79,999", "$80,000 to $84,999", "$85,000 to $89,999", "$125,000 to $149,999", "$150,000 to $174,999"],
})
const genders = ref([
  { label: '男', value: 'Male' },
  { label: '女', value: 'Female' },
  { label: '随机', value: 'Random' },
])

const employments = ref([
  {
    label: '全职就业',
    value: 'Employed full-time',
  },
  {
    label: '兼职就业',
    value: 'Employed part-time',
  },
  {
    label: '全职自主创业',
    value: 'Self-employed full-time',
  },
  {
    label: '兼职自主创业',
    value: 'Self-employed part-time',
  },
  {
    label: '现役军人',
    value: 'Active military',
  },
  {
    label: '非现役军人/退伍军人',
    value: 'Inactive military/Veteran',
  },
  {
    label: '暂时失业',
    value: 'Temporarily unemployed',
  },
  {
    label: '全职家庭主妇/夫',
    value: 'Full-time homemaker',
  },
  {
    label: '退休',
    value: 'Retired',
  },
  {
    label: '学生',
    value: 'Student',
  },
  {
    label: '残疾人士',
    value: 'Disabled',
  },
  {
    label: '不愿回答',
    value: 'Prefer not to answer',
  },
  {
    label: '育儿假',
    value: 'Parental leave',
  },
  {
    label: '休假',
    value: 'Leave of absence',
  },
  {
    label: '无法工作',
    value: 'Unable to work',
  },
  {
    label: '其他有薪工作',
    value: 'Other type of paid work',
  },
  {
    label: '抚养家庭',
    value: 'Bringing up a family',
  },
  {
    label: '全职无薪工作',
    value: 'Unpaid full-time career',
  },
  {
    label: '无薪工作',
    value: 'Working unpaid',
  },
  {
    label: '待业/正在找工作',
    value: 'In-between jobs / looking for work',
  },
])
const educations = ref([
  {
    label: '三年级及以下',
    value: '3rd Grade or less',
  },
  {
    label: '中学 - 四至八年级',
    value: 'Middle School - Grades 4 - 8',
  },
  {
    label: '完成部分高中学业',
    value: 'Completed some high school',
  },
  {
    label: '高中毕业',
    value: 'High school graduate',
  },
  {
    label: '高中毕业后的其他职业培训',
    value: 'Other post high school vocational training',
  },
  {
    label: '完成部分大学学业，但未获得学位',
    value: 'Completed some college, but no degree',
  },
  {
    label: '副学士学位',
    value: 'Associate Degree',
  },
  {
    label: '大学学位',
    value: 'College Degree (such as B.A., B.S.)',
  },
  {
    label: '完成部分研究生学业，但未获得学位',
    value: 'Completed some graduate, but no degree',
  },
  {
    label: '硕士学位',
    value: 'Masters degree',
  },
  {
    label: '博士学位',
    value: 'Doctorate degree',
  },
])
const incomes = ref([
    { label: "<1.5", value: "Less than $14,999" },
    { label: "1.5-1.9", value: "$15,000 to $19,999" },
    { label: "2-2.4", value: "$20,000 to $24,999" },
    { label: "2.5-2.9", value: "$25,000 to $29,999" },
    { label: "3-3.4", value: "$30,000 to $34,999" },
    { label: "3.5-3.9", value: "$35,000 to $39,999" },
    { label: "4-4.4", value: "$40,000 to $44,999" },
    { label: "4.5-4.9", value: "$45,000 to $49,999" },
    { label: "5-5.4", value: "$50,000 to $54,999" },
    { label: "5.5-5.9", value: "$55,000 to $59,999" },
    { label: "6-6.4", value: "$60,000 to $64,999" },
    { label: "6.5-6.9", value: "$65,000 to $69,999" },
    { label: "7-7.4", value: "$70,000 to $74,999" },
    { label: "7.5-7.9", value: "$75,000 to $79,999" },
    { label: "8-8.4", value: "$80,000 to $84,999" },
    { label: "8.5-8.9", value: "$85,000 to $89,999" },
    { label: "9-9.4", value: "$90,000 to $94,999" },
    { label: "9.5-9.9", value: "$95,000 to $99,999" },
    { label: "10-12.4", value: "$100,000 to $124,999" },
    { label: "12.5-14.9", value: "$125,000 to $149,999" },
    { label: "15-17.4", value: "$150,000 to $174,999" },
    { label: "17.5-19.9", value: "$175,000 to $199,999" },
    { label: "20-24.9", value: "$200,000 to $249,999" },
    { label: "25+", value: "$250,000 and above" }
])
const genderVal = ref('Random')

const recordForm = reactive({})
const recordData = ref('')
const ipinfo = ref({})
const loading = ref(false)
const disabled = ref(false)

// 下一步点击
const handleClickNext = (timeout = 1500) => {
  delay(timeout).then(() => {
    const nextBtn = document.querySelectorAll('button.next_btn')
    if (nextBtn && nextBtn.length) {
      let lastBtn = nextBtn[nextBtn.length - 1]
      if (lastBtn.disabled) {
        lastBtn.disabled = false
      }
      lastBtn.click()
    } else {
      delay(1000).then(() => {
        const nextBtn = document.querySelectorAll('button.next_btn')
        if (nextBtn && nextBtn.length) {
          let lastBtn = nextBtn[nextBtn.length - 1]
          lastBtn.disabled = false
          lastBtn.click()
        }
      })
    }
  })
}

const handleGenderUpdateValue = (e) => {
  setItem('genderVal', e.target.value)
}

const handleEducationUpdateValue = (value) => {
  setItem('educationVal', value)
}

const handleJobUpdateValue = (value) => {
  console.log('value: ', value);
  setItem('employmentVal', value)
}

const handleIncomeUpdateValue = (value) => {
  setItem('incomeVal', value)
}

const updateRecordData = () => {
  // 格式化数据
  const formattedText = Object.values(recordForm)
    .map(({ label, value }) => {
      return value ? `${label}：${value}` : ''
    })
    .filter(Boolean)
    .join('\n')

  setItem('kkForm', formattedText)
  recordData.value = formattedText
}

// 操作执行
const actionHandle = () => {
  // 处理邮政编码
  const handlePostal = function () {
    console.log('邮编')
    if (ipinfo.value.ip_data) {
      const postalInput = document.querySelector('input[name="selectedInputOptField"]')
      if (postalInput) {
        recordForm.zipcode = { label: '邮编', value: ipinfo.value.ip_data.zipcode }
        updateRecordData()
        postalInput.value = ipinfo.value.ip_data.zipcode
        postalInput.dispatchEvent(new Event('input', { bubbles: true }))
        delay(500).then(() => {
          handleClickNext()
        })
      }
    }
  }

  // 处理家庭收入
  const handleHouseholdIncome = function () {
    console.log('家庭收入',)
    let options = formValue.income
    if (formValue.income.length === 0) {
      options = incomes.value.map((opt) => opt.value)
    }
    randomSelectRadioBySelectors(...options.map((opt) => `input[type="radio"][value*="${opt}"]`))
      .then((val) => {
        recordForm.householdIncome = { label: '家庭收入', value: val }
        updateRecordData()
        handleClickNext()
      })
      .catch(() => {
        checkTextChange('h5.question-text', actionHandle())
      })
  }

  // 处理种族
  const handleRace = function () {
    console.log('race')
    randomSelectRadioBySelectors('input[value="White"]')
      .then((val) => {
        recordForm.race = { label: '种族', value: val }
        updateRecordData()
        handleClickNext()
      })
      .catch(() => {
        checkTextChange('h5.question-text', actionHandle())
      })
  }

  // 处理年龄
  const handleAge = function () {
    console.log('age')
    let minAge = formValue.age[0]
    let maxAge = formValue.age[1]
    let ageVal = getRandomIntInRange(minAge, maxAge)
    const ageInput = document.querySelector('input[max="99"]')
    if (ageInput) {
      ageInput.value = ageVal
      recordForm.ages = { label: '年龄', value: ageVal }
      updateRecordData()
      ageInput.dispatchEvent(new Event('input', { bubbles: true }))

      handleClickNext()
    }
  }

  // 处理性别
  const handleGender = function () {
    console.log('性别')
    let selectorStr = ''
    if (genderVal.value === 'Male') {
      selectorStr = 'input[value="Male"]'
    } else if (genderVal.value === 'Female') {
      selectorStr = 'input[value="Female"]'
    } else {
      selectorStr = 'input[value="Male"], input[value="Female"]'
    }
    randomSelectRadioBySelectors(selectorStr)
      .then((val) => {
        recordForm.gender = { label: '性别', value: val }
        updateRecordData()
        handleClickNext()
      })
      .catch(() => {
        checkTextChange('h5.question-text', actionHandle())
      })
  }

  // 处理职业
  const handleEmployment = function () {
    console.log('职业状态')
    let options = formValue.employment
    if (formValue.employment.length === 0) {
      options = employments.value.map((opt) => opt.value)
    }
    randomSelectRadioBySelectors(...options.map((opt) => `input[type="radio"][value*="${opt}"]`))
      .then((val) => {
        recordForm.jobStatus = { label: '职业状态', value: val }
        updateRecordData()
        handleClickNext()
      })
      .catch(() => {
        checkTextChange('h5.question-text', actionHandle())
      })
  }

  // 处理是否是 Hispanic
  const handleHispanic = function () {
    console.log('Hispanic')
    randomSelectRadioBySelectors('input[value="No"]').catch(() => {
      checkTextChange('h5.question-text', actionHandle())
    })
    handleClickNext()
  }

  // 处理教育程度
  const handleEducation = function () {
    console.log('education')
    let options = formValue.education
    if (formValue.education.length === 0) {
      options = educations.value.map((opt) => opt.value)
    }
    randomSelectRadioBySelectors(...options.map((opt) => `input[type="radio"][value*="${opt}"]`))
      .then((val) => {
        recordForm.education = { label: '学历', value: val }
        updateRecordData()
        handleClickNext()
      })
      .catch(() => {
        checkTextChange('h5.question-text', actionHandle())
      })
  }

  // **不同 key 组对应不同的处理函数**
  const methodMappings = [
    { keys: ['postal', 'zip'], handler: handlePostal },
    { keys: ['household income'], handler: handleHouseholdIncome },
    { keys: ['race'], handler: handleRace },
    { keys: ['age'], handler: handleAge },
    { keys: ['gender'], handler: handleGender },
    { keys: ['employment'], handler: handleEmployment },
    { keys: ['Hispanic'], handler: handleHispanic },
    { keys: ['education'], handler: handleEducation },
  ]

  // **动态生成 action 对象**
  return methodMappings.reduce((actions, { keys, handler }) => {
    keys.forEach((key) => (actions[key] = handler))
    return actions
  }, {})
}

// 手动执行
const handleValidateSubmit = () => {
  runStatus.value = !runStatus.value
  setItem('kk-run-status', runStatus.value)
  if (runStatus.value) {
    handleAction()
  } else {
    clearInterval(checkInnInitLoadingTimer)
    clearInterval(checkInnLetGoTimer)
  }
}

const handleAction = () => {
  getItem('innovatemrType').then((value) => {
    if (value) {
      checkTextChange('h5.question-text', actionHandle())
      observeTextChange('h5.question-text', actionHandle())
    } else {
      message.value = '此网站不支持使用'
    }
  })
}

const matchHost = () => {
  let href = location.href
  let matchedElement = allowHost.find((item) => href.includes(item.host))
  if (matchedElement) {
    disabled.value = false
  } else {
    disabled.value = true
  }
}

const ageChangeHandle = (val) => {
  if (val && val.length) {
    setItem('kk-age', val)
  }
}

const checkTextChange = async (selector, logicMap) => {
  await delay(1000)
  if (!runStatus.value) return
  const element = document.querySelector(selector)
  if (!element) {
    console.log(`未找到选择器 "${selector}" 对应的元素`)
    return
  }
  const newText = element.textContent.trim()
  for (const key in logicMap) {
    if (newText.includes(key)) {
      logicMap[key]() // 执行相应的逻辑
      break // 找到匹配的逻辑后可以跳出循环
    }
  }
}

const observeTextChange = (selector, logicMap) => {
  const element = document.querySelector(selector)
  if (!element) {
    console.log(`未找到选择器 "${selector}" 对应的元素`)
    return
  }

  const observer = new MutationObserver(function (mutations) {
    if (!runStatus.value) return
    mutations.forEach(function (mutation) {
      // 获取当前文本内容
      const newText = element.textContent.trim()
      if (newText !== mutation.oldValue?.trim()) {
        // 确保文本内容发生了变化
        // 根据不同的文本包含关系执行不同的逻辑
        for (const key in logicMap) {
          if (newText.includes(key)) {
            delay(1000).then(() => {
              logicMap[key]() // 执行相应的逻辑
            })
            break // 找到匹配的逻辑后可以跳出循环
          }
        }
      }
    })
  })

  observer.observe(element, {
    childList: true, // 观察子节点的变化
    subtree: true, // 观察所有后代节点的变化
    characterData: true, // 观察文本节点内容的变化
    characterDataOldValue: true, // 保留变化前的文本值
  })

  console.log(`开始观察元素 ${selector} 的文本变化`)
}

// 检测初次进入页面 loading加载
let checkInnInitLoadingTimer = ref(null)
const checkInnInitLoading = (timeout = 30000) => {
  clearInterval(checkInnInitLoadingTimer)
  return new Promise((resolve, reject) => {
    let elapsedTime = 0
    const interval = 500

    checkInnInitLoadingTimer = setInterval(() => {
      let innLoading = document.querySelector('.mat-mdc-progress-spinner')

      if (!innLoading) {
        console.log('加载完成')
        clearInterval(checkInnInitLoadingTimer)
        resolve('加载完成') // 任务完成，返回成功
      }

      elapsedTime += interval
      if (elapsedTime >= timeout) {
        console.log('加载超时')
        clearInterval(checkInnInitLoadingTimer)
        reject('加载超时,请刷新页面重试') // 超时，返回失败
      }
    }, interval)
  })
}

// 检测https://edgesurvey.innovatemr.net/页面的 let go按钮
let checkInnLetGoTimer = ref(null)
const checkInnLetGoBtn = (timeout = 20000) => {
  clearInterval(checkInnLetGoTimer)
  return new Promise((resolve, reject) => {
    let elapsedTime = 0
    const interval = 500

    checkInnLetGoTimer = setInterval(() => {
      let letGoBtn = document.querySelector('button[translate="srvyFinal.btnLtsDo"]')

      if (letGoBtn) {
        clearInterval(checkInnLetGoTimer)
        runStatus.value = false
        setItem('kk-run-status', false)
        setItem('kkhide', false)
        letGoBtn.click()
        resolve('加载完成') // 任务完成，返回成功
      }

      elapsedTime += interval
      if (elapsedTime >= timeout) {
        console.log('加载超时')
        clearInterval(checkInnLetGoTimer)
        reject('加载超时,请刷新页面重试') // 超时，返回失败
      }
    }, interval)
  })
}

onMounted(() => {
  // matchHost()

  // 获取本地信息
  getItem('ipinfo').then((value) => {
    if (value) {
      ipinfo.value = value
    }
  })
  getItem('kk-age').then((value) => {
    if (value) {
      formValue.age = value
    }
  })

  getItem('kk-run-status').then((value) => {
    if (value) {
      runStatus.value = value
    } else {
      runStatus.value = false
    }
  })

  getItem('genderVal').then((value) => {
    if (value) {
      genderVal.value = value
    }
  })

  getItem('educationVal').then((value) => {
    if (value) {
      formValue.education = value
    }
  })

  getItem('employmentVal').then((value) => {
    console.log('value: ', value);
    if (value) {
      formValue.employment = value
    }
  })

  getItem('incomeVal').then((value) => {
    if (value) {
      formValue.income = value
    }
  })

  getItem('kkForm').then((value) => {
    if (value) {
      recordData.value = value
    }
  })

  if (location.host === 'edgesurvey.innovatemr.net') {
    getItem('innovatemrType').then((value) => {
      console.log('innovatemrType: ', value)
      if (value) {
        checkInnLetGoBtn(60000)
      } else {
        emit('hideCrx', true)
      }
    })
  }

  // 检测是否加载完成
  if (location.host === 'route.innovatemr.net') {
    setItem('innovatemrType', 'route')
    emit('hideCrx', false)
    checkInnInitLoading(60000)
      .then((message) => {
        handleAction()
      })
      .catch((error) => {
        console.log(error)
        message.value = error
      })
  } else {
    getItem('innovatemrType').then((value) => {
      if (!value) {
        emit('hideCrx', true)
      }
    })
  }
})
</script>

<template>
  <main class="kk-index">
    <h3 class="kk-h3">B</h3>
    <n-form label-placement="left" label-width="40" ref="formRef" size="small" :model="formValue" style="display: block !important">
      <n-form-item label="年龄" path="query">
        <n-input pair separator="-" @change="ageChangeHandle" v-model:value="formValue.age" />
      </n-form-item>
      <n-form-item label="性别" path="scrnshBtm">
        <n-radio-group v-model:value="genderVal" @change="handleGenderUpdateValue" name="gender">
          <n-radio :value="item.value" v-for="item in genders" :key="item.value">
            {{ item.label }}</n-radio
          >
        </n-radio-group>
      </n-form-item>
      <n-form-item label="学历" path="education">
        <n-select clearable :max-tag-count="3" v-model:value="formValue.education" multiple :options="educations" @change="handleEducationUpdateValue" />
      </n-form-item>
      <n-form-item label="工作" path="employments">
        <n-select clearable v-model:value="formValue.employment" multiple :options="employments" @change="handleJobUpdateValue" />
      </n-form-item>
      <n-form-item label="收入(万)" path="income">
        <n-select clearable :max-tag-count="3" v-model:value="formValue.income" multiple :options="incomes" @change="handleIncomeUpdateValue" />
      </n-form-item>
      <n-form-item label="数据" path="data">
        <n-input type="textarea" rows="4" readonly v-model:value="recordData" placeholder="Info" />
      </n-form-item>
      <n-form-item>
        <n-button
          style="width: 100%"
          attr-type="button"
          color="#8a2be2"
          :loading="loading"
          :disabled="disabled"
          @click="handleValidateSubmit"
        >
          {{ runStatus ? '执行中' : '执行' }}
        </n-button>
      </n-form-item>
    </n-form>
    <p style="color: red" v-if="message">{{ message }}</p>
  </main>
</template>

<style></style>
